<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://music.yandex.ru/index.css" />
  </head>
  <body>
    <div style="padding: 24px;" class="typo-main theme-white">
      <div id="input-url-wrapper" class="d-input deco-input-wrapper deco-input-wrapper_suggest d-input_size-L">
        <input id="input-url" type="text" class="d-input__field deco-input deco-input_suggest" placeholder="Yandex Music URL">
        <div class="d-input__tip deco-input__tip"></div>
      </div>
      <button id="navigate-button" class="d-button deco-button deco-button-action" type="button">
        <span class="d-button-inner deco-button-stylable" style="height: 40px;">
          <span class="d-button__inner">
            <span class="d-icon deco-icon d-icon_arrow-right "></span>
          </span>
        </span>
      </button>
    </div>
  </body>
</html>
<script>
  const ipc = require("electron").ipcRenderer;

  const inputWrapperErrorClass = "deco-input-wrapper_fail";
  const yandexMusicUrl = "https://music.yandex.ru";

  let inputURL = document.getElementById("input-url");
  let inputURLWrapper = document.getElementById("input-url-wrapper");

  document.getElementById("navigate-button").addEventListener("click", navigateToURLFromInput);

  const darkModeWatchMedia = window.matchMedia("(prefers-color-scheme: dark)");
  darkModeWatchMedia.addEventListener("change", (e) => {
    switchViewMode(e.matches);
  });
  switchViewMode(darkModeWatchMedia.matches);

  ipc.on("url", (_event, url) => {
    inputURL.value = url;
    inputURL.select();
  });

  document.addEventListener("keydown", event => {
    if (event.key === "Escape") {
      window.close();
    }
    if (event.key === "Enter") {
      navigateToURLFromInput();
    }
  });

  inputURL.addEventListener("keyup", () => {
    if (inputURLWrapper.classList.contains(inputWrapperErrorClass) && isYandexMusicUrl(inputURL.value)) {
      inputURLWrapper.classList.remove(inputWrapperErrorClass);
    }
  });

  function navigateToURLFromInput() {
    let url = inputURL.value;
    if (isYandexMusicUrl(url)) {
      let relativeUrl = url.slice(yandexMusicUrl.length);
      ipc.send("navigate", relativeUrl);
    } else {
      inputURLWrapper.classList.add(inputWrapperErrorClass);
    }
  }

  function isYandexMusicUrl(url) {
    return url.startsWith(yandexMusicUrl);
  }

  function switchViewMode(isDarkMode) {
    if (isDarkMode) {
      document.body.className = "theme theme_dark deco-pane-body black theme-black action-icon-theme-white layout_narrow";
    } else {
      document.body.className = "deco-pane-body black layout_narrow theme-white action-icon-theme-white";
    }
  }
</script>
